﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MotionControl.Modules.RestService.Controllers
{
    public class WSHandler
    {
        private readonly WebSocketConnections _connections;

        public WSHandler(WebSocketConnections connections)
        {
            _connections = connections;
        }

        public async Task HandleConnection(WebSocket webSocket)
        {
            _connections.Add(webSocket);

            try
            {
                byte[] buffer = new byte[1024];
                WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

                while (!result.CloseStatus.HasValue)
                {
                    string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
                    await ProcessMessage(message);

                    result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                }

                await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
            }
            finally
            {
                // 从连接管理器中移除WebSocket连接
                _connections.Remove(webSocket);
            }
        }

        private async Task ProcessMessage(string message)
        {
            Debug.WriteLine(message);
        }
    }
}
